/**
 * @param dir '.'
 * @param port 80
 */
const dir = process.argv[2] || ".";
const port = process.argv[3] || 80;

const { stat, createReadStream } = require("fs");
const http = require("http");
const path = require("path");

const resolveFile = (filepath, response) => {
  stat(filepath, (err, stats) => {
    console.log(filepath);
    if (!err && stats.isFile()) {
      response.writeHead(200);
      createReadStream(filepath).pipe(response);
    } else if (!err && stats.isDirectory()) {
      resolveFile(filepath + "index.html", response);
    } else {
      response.writeHead(404);
      response.end(`404 Not Found`);
    }
  });
};

const server = http.createServer((request, response) => {
  console.log(request.url);
  const root = path.resolve(dir);
  const { pathname } = new URL(request.url, `http://${request.headers.host}`);
  const filepath = path.join(root, pathname);
  resolveFile(filepath, response);
});

server.listen(port);

console.log(`listening at http://localhost:${port}`);
